// src\lang\storageType.ts
import { local } from '@/utils/storage'
import { createI18n } from 'vue-i18n'
import { LANG_VALUE } from '@/common/enum'
import useLangStore from '@/stores/modules/lang'
import zhCn from './zh-cn'
import en from './en'
import { storeToRefs } from 'pinia'

export function getLanguage(): string {
  const chooseLanguage = local.get<{ language: string }>('language')
  if (chooseLanguage) return chooseLanguage.language
  const language = navigator.language.toLowerCase()
  const locales = [LANG_VALUE.En, LANG_VALUE.Zh]
  for (const locale of locales) {
    if (language.indexOf(locale) > -1) {
      return locale
    }
  }
  return LANG_VALUE.Zh
}

export function setLocale(lang: string) {
  // 获取当前语言
  const useLanguage = useLangStore()
  const { language } = storeToRefs(useLanguage)
  i18n.global.locale.value = lang as LANG_VALUE // 修改 i18n
  language.value = lang // 修改 pinia
}

const i18n = createI18n({
  legacy: false,
  locale: getLanguage(),
  fallbackLocale: LANG_VALUE.Zh, // 设置备用语言
  messages: {
    [LANG_VALUE.Zh]: zhCn,
    [LANG_VALUE.En]: en,
  },
})
export default i18n
